package com.third.controller;

import com.third.entity.RestBean;
import com.third.entity.Users;
import com.third.entity.vo.request.ConfirmResetVo;
import com.third.entity.vo.request.EmailRegisterVO;
import com.third.entity.vo.request.EmailResetVO;
import com.third.service.UsersService;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Pattern;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * @author 唐博文
 * @version 2023.1.2
 * @date 2023/10/24 20:43 星期二
 */
@Validated
@RestController
@RequestMapping("/api/auth")
public class AuthorizeController {
    
    @Resource
    UsersService service;
    
    @PostMapping("/register")
    public RestBean<Void> register(@RequestBody @Valid EmailRegisterVO vo){
        System.out.println("EmailRegisterVO===="+vo);
        return this.messageHandle(vo,service::registerEmailUsers);
    }
    
    //验证码是否正确
    @GetMapping("/ask-code")
    public RestBean<Void> askVerifyCode(@RequestParam @Email String email,
                                        @RequestParam @Pattern(regexp = "(register|reset)") String type,
                                        HttpServletRequest request){
        //System.out.println("email::"+email+"   "+"type==="+type+"   "+request.getRemoteAddr());
        //String message=service.registerEmailVerifyCode(type,email,"192.168.2.130");
        //System.out.println("message====="+message);
        Users account = service.findUsersByNameOrEmail(email);
        if (type.equals("reset")&&account==null)
            return RestBean.failure(400,"用户不存在");
        return this.messageHandle(()-> service.registerEmailVerifyCode(type,email,request.getRemoteAddr()));
    }
    //判断重置密码所需的验证码是否正确
    @PostMapping("/reset-confirm")
    public RestBean<Void> resetConfirm(@RequestBody @Valid ConfirmResetVo vo){
        return this.messageHandle(vo,service::resetConfirm);
    }
    
    @PostMapping("/reset-password")
    public RestBean<Void> resetConfirm(@RequestBody @Valid EmailResetVO vo){
        return this.messageHandle(vo,service::resetEmailUsersPassword);
    }
    
    private <T> RestBean<Void> messageHandle(T vo, Function<T,String> function){
        return messageHandle(()->function.apply(vo));
    }
    
    private RestBean<Void> messageHandle(Supplier<String> action){
        String message=action.get();
        return message==null ? RestBean.success():RestBean.failure(400,message);
    }
    
    
    
    
    
    
    
    
    
    
}
